package com.campus.counseling.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.campus.counseling.entity.SysUser;
import com.campus.counseling.model.mapper.SysUserMapper;
import com.campus.counseling.security.SecurityUser;
import com.campus.counseling.service.SysMenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final SysUserMapper userMapper;
    private final SysMenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        SysUser user = userMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, username));

        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 查询用户权限信息
        List<String> permissions = menuService.getPermissionsByUserId(user.getId());
        
        // 查询用户角色
        List<String> roles = userMapper.selectUserRoles(user.getId());
        
        // 创建权限列表
        List<String> authorities = new ArrayList<>();
        
        // 添加权限
        if (permissions != null) {
            authorities.addAll(permissions.stream()
                .filter(perm -> perm != null && !perm.trim().isEmpty())
                .collect(Collectors.toList()));
        }
        
        // 添加角色
        if (roles != null) {
            authorities.addAll(roles.stream()
                .filter(role -> role != null && !role.trim().isEmpty())
                .map(role -> "ROLE_" + role)
                .collect(Collectors.toList()));
        }
        
        // 如果没有任何权限，至少添加一个基础用户角色
        if (authorities.isEmpty()) {
            authorities.add("ROLE_USER");
        }

        return new SecurityUser(user, authorities);
    }
} 